﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HY.Utility.Net;
using System.Text.RegularExpressions;
using HY.Utility.Extension;
using System.Data;
using HY.Utility.Enum;

namespace HYDataCapture.Presenters
{
    public class Win007DataCapturePresenter
    {
        private readonly Views.IWin007DataCaptureView _View;
        private List<Models.Win007TreeNodeDataIndexModel> _TreeNodeDataIndexList;
        private List<Models.Win007MatchModel> _MatchList;
        private List<Models.Win007MatchResultModel> _MatchResultList;

        /// <summary>
        /// 发生错误时间
        /// </summary>
        private DateTime _ErrorStartTime;


        public Win007DataCapturePresenter(Views.IWin007DataCaptureView view)
        {
            _View = view;
            _MatchList = new List<Models.Win007MatchModel>();
        }

        public List<Models.Win007TreeNodeDataModel> TreeNodeDataList { get; private set; }

        private List<Models.Win007TreeNodeDataModel> AnalysisTextToNode(string text)
        {
            var output = new List<Models.Win007TreeNodeDataModel>();

            var ms = Regex.Matches(text, "\\[\\\"\\d+[^\\]]+");
            if (ms.Count > 0)
            {
                foreach (Match m in ms)
                {
                    var ms2 = Regex.Matches(m.Value, "\\d+,[\\u4e00-\\u9fa5]+[^\\\"]+");
                    foreach (Match m2 in ms2)
                    {
                        var sps = m2.Value.Split(',');
                        string id = sps[0];
                        string name = sps[1];
                        string key1 = sps[2];
                        string key2 = sps[3];

                        var sub = "";
                        var key = $"{key1}|{key2}";
                        switch (key)
                        {
                            case "1|0":
                                sub = "League";
                                break;
                            case "1|1":
                                sub = "SubLeague";
                                break;
                            case "2|0":
                            case "2|1":
                                sub = "CupMatch";
                                break;
                            default:
                                throw new Exception($"{key}");
                        }

                        var mainnode = new Models.Win007TreeNodeDataModel()
                        {
                            Text = name,
                            IsOnlyTitle = true,
                            ChildNodeList = new List<Models.Win007TreeNodeDataModel>()
                        };
                        _TreeNodeDataIndexList.Add(new Models.Win007TreeNodeDataIndexModel() { Id = mainnode.Id, Node = mainnode });
                        for (var i = 4; i < sps.Length; ++i)
                        {
                            string time_range = sps[i];

                            var url2 = $"http://zq.win007.com/cn/{sub}/{time_range}/{id}.html";
                            var node = new Models.Win007TreeNodeDataModel()
                            {
                                Text = name + time_range,
                                IsOnlyTitle = false,
                                Url = url2
                            };
                            _TreeNodeDataIndexList.Add(new Models.Win007TreeNodeDataIndexModel() { Id = node.Id, Node = node });
                            mainnode.ChildNodeList.Add(node);
                        }
                        output.Add(mainnode);


                    }
                }
            }
            return output;
        }

        public bool DataMenuUrlCapture()
        {
            var output = false;
            do
            {

                TreeNodeDataList = new List<Models.Win007TreeNodeDataModel>();
                _TreeNodeDataIndexList = new List<Models.Win007TreeNodeDataIndexModel>();

                string url = "http://zq.win007.com/jsData/infoHeader.js";
                HttpHead head = new HttpHead() { Url = url, Method = "GET" };

                _View.Log = $"正在请求：{url}";
                var result = HttpHelper.SendHttpRequest(ref head);
                if (result.Length == 0 || !head.Result_Success)
                {
                    _View.Log = $"返回出错：状态码({head.Result_StatusCode}){head.Result_Exception}";
                    break;
                }
                _View.Log = $"正在解析数据...";

                {
                    List<string> textList = new List<string>();
                    var ms = Regex.Matches(result, "InfoID_\\d+\\\",\\\"[^\\\"]+");
                    foreach (Match m in ms)
                    {
                        var startindex = result.IndexOf(m.Value);
                        if (startindex != -1)
                        {
                            var text = result.Substring(startindex);
                            int endindex = text.IndexOf("]]");
                            if (endindex != -1)
                            {
                                text = text.Substring(0, endindex);
                                textList.Add(text);
                            }
                        }
                    }
                    textList.ForEach(s =>
                    {
                        var m = Regex.Match(s, "InfoID_\\d+\\\",\\\"[^\\\"]+");
                        if (m.Success)
                        {
                            var countryGame = Regex.Replace(m.Value, "InfoID_\\d+\\\",\\\"", "");
                            if (!string.IsNullOrEmpty(countryGame))
                            {
                                Models.Win007TreeNodeDataModel node = new Models.Win007TreeNodeDataModel();
                                node.Text = countryGame;
                                node.IsOnlyTitle = true;
                                node.ChildNodeList = AnalysisTextToNode(s);
                                TreeNodeDataList.Add(node);
                                _TreeNodeDataIndexList.Add(new Models.Win007TreeNodeDataIndexModel() { Id = node.Id, Node = node });
                            }
                        }
                    });

                }
                _View.Log = $"解析完成.";
                output = true;
            } while (false);

            return output;
        }

        public Models.Win007TreeNodeDataModel GetTreeNodeData(string id)
        {
            Models.Win007TreeNodeDataModel output = null;
            do
            {
                var data = _TreeNodeDataIndexList.Find(s => s.Id == id);
                if (data == null)
                {
                    _View.Log = "未能找出数据";
                    break;
                }
                //if (TreeNodeDataList.Count < data.Index)
                //{
                //    _View.Log = "超出范围";
                //    break;
                //}
                //var node = TreeNodeDataList[data.Index].ChildNodeList.Find(s => s.Id == id);
                output = data.Node;
            } while (false);
            return output;
        }

        private string GetLetGoal(decimal goal)
        {
            var GoalCn = new string[] { "平手", "平/半", "半球", "半/一", "一球", "一/球半", "球半", "半/二", "二球", "二/半", "二球半", "半/三", "三球", "三/半", "三球半", "半/四", "四球", "四/半", "四球半", "半/五", "五球", "五/半", "五球半", "五球半/六球", "六球", "六球/六球半", "六球半", "六球半/七球", "七球", "七球/七球半", "七球半", "七球半/八球", "八球", "八球/八球半", "八球半", "八球半/九球", "九球", "九球/九球半", "九球半", "九球半/十球", "十球" };
            var GoalEn = new string[] { "0", "0/0.5", "0.5", "0.5/1", "1", "1/1.5", "1.5", "1.5/2", "2", "2/2.5", "2.5", "2.5/3", "3", "3/3.5", "3.5", "3.5/4", "4", "4/4.5", "4.5", "4.5/5", "5", "5/5.5", "5.5", "5.5/6", "6", "6/6.5", "6.5", "6.5/7", "7", "7/7.5", "7.5", "7.5/8", "8", "8/8.5", "8.5", "8.5/9", "9", "9/9.5", "9.5", "9.5/10", "10" };

            var Goal2GoalCn = "";
            var goalKind = Convert.ToInt32(goal * 4.0m);
            if (goal >= 0)
            {
                Goal2GoalCn = GoalCn[goalKind] + "|" + GoalEn[goalKind];
            }
            else
            {
                goalKind = Math.Abs(goalKind);
                var enGoals = GoalEn[goalKind].Split('/');
                var s = "";
                if (enGoals[0] != "0")
                {//第一个数字为0则不显示负号
                    if (enGoals.Length == 2)
                        s = "-" + enGoals[0] + "/-" + enGoals[1];
                    else
                        s = "-" + enGoals[0];
                }
                else
                {
                    if (enGoals.Length == 2)
                        s = enGoals[0] + "/-" + enGoals[1];
                    else
                        s = enGoals[0];
                }

                Goal2GoalCn = "*" + GoalCn[goalKind] + "|" + s;
            }
            return Goal2GoalCn.Split('|')[0];
        }

        private void HandleCaptureDataContent(string lunci, string text, Dictionary<string, string> dicMatch, List<Models.Win007MatchModel> matchList)
        {
            var ms = Regex.Matches(text, "\\[\\d+[^\\]]+");
            foreach (Match m in ms)
            {
                var raw_value = m.Value;
                var r_index = raw_value.IndexOf("[");
                while (r_index != -1)
                {
                    raw_value = raw_value.Substring(r_index);
                    raw_value = raw_value.TrimStart('[');
                    r_index = raw_value.IndexOf("[");
                }
                var value = raw_value.TrimStart('[').Replace("'", "");
                var sps = value.Split(',');
                if (sps.Length > 20)
                {
                    Models.Win007MatchModel model = new Models.Win007MatchModel()
                    {
                        Id = sps[0],
                        HomeTeam = dicMatch[sps[4].TrimStart('[')],
                        Score = sps[6],
                        VisitingTeam = dicMatch[sps[5].TrimStart('[')],
                        LunCi = lunci,
                        Time = sps[3],
                        MatchResult = "-",
                        RangQiuQuanChang = "",
                    };
                    if (!string.IsNullOrEmpty(sps[10]))
                        model.RangQiuQuanChang = GetLetGoal(Convert.ToDecimal(sps[10]));
                    var sps2 = model.Score.Split('-');
                    if (sps2.Length > 1)
                    {
                        var num1 = -1;
                        var num2 = -1;
                        int.TryParse(sps2[0], out num1);
                        int.TryParse(sps2[1], out num2);
                        if (num1 != -1 && num2 != -1)
                        {
                            var r = num1 - num2;
                            if (r > 0)
                                model.MatchResult = "胜";
                            else if (r < 0)
                                model.MatchResult = "负";
                            else
                                model.MatchResult = "平";
                        }
                    }
                    matchList.Add(model);
                }
            }
        }

        public void Init()
        {
            _View.MatchSaveItems = EnumAttributeHelper.GetEnumDescription(typeof(Enums.Win007MatchSaveOptionEnum)).ToArray();
            _View.MatchId = new Models.Win007MatchModel().GetDescription("Id");
        }

        public DataTable DataCapture(Models.Win007TreeNodeDataModel input)
        {
            DataTable output = new DataTable();

            var columns = new Models.Win007MatchModel().GetDescriptions();
            foreach (var col in columns)
                output.Columns.Add(col, typeof(string));

            var urlItems = input.Url.Split('|');
            bool isLoopMatch = urlItems.Length > 1;
            if (_View.MatchSaveOption == Enums.Win007MatchSaveOptionEnum.NotSave)
                _MatchList.Clear();
            foreach(var urlItem in urlItems)
            {
                do
                {
                    HttpHead head = new HttpHead() { Url = urlItem, Method = "GET" };
                    _View.Log = $"正在请求：{head.Url}";
                    var result = HttpHelper.SendHttpRequest(ref head);
                    if (result.Length == 0 || !head.Result_Success)
                    {
                        _View.Log = $"{head.Url}下载出错";
                        break;
                    }
                    var ms = Regex.Matches(result, "<script[^>]+");
                    var data_url = "";
                    foreach (Match m in ms)
                    {
                        var m2 = Regex.Match(m.Value, "/jsData/matchResult/[^\"]+");
                        if (m2.Success)
                        {
                            data_url = HttpHelper.GetFullUrl(head.Url, m2.Value);
                            break;
                        }
                    }
                    if (data_url.Length == 0)
                    {
                        _View.Log = "无法获取数据URL";
                        break;
                    }
                    head.Url = data_url;
                    _View.Log = $"正在请求：{head.Url}";
                    result = HttpHelper.SendHttpRequest(ref head);
                    if (result.Length == 0 || !head.Result_Success)
                    {
                        _View.Log = $"{head.Url}下载出错";
                        break;
                    }
                    _View.Log = $"正在解析数据...";
                    var m3 = Regex.Match(result, "arrTeam\\s+=\\s+\\[\\[");
                    if (!m3.Success)
                    {
                        _View.Log = "未能匹配";
                        break;
                    }
                    var startindex = result.IndexOf(m3.Value);
                    if (startindex == -1)
                    {
                        _View.Log = "超出范围";
                        break;
                    }
                    var text = result.Substring(startindex);
                    var endindex = text.IndexOf("]]");
                    if (endindex == -1)
                    {
                        _View.Log = "超出范围";
                        break;
                    }
                    text = text.Substring(0, endindex);

                    Dictionary<string, string> dicMatch = new Dictionary<string, string>();
                    ms = Regex.Matches(text, "\\[\\d+,'[^']+");
                    foreach (Match m in ms)
                    {
                        var temp = m.Value.Replace("[", "");
                        temp = temp.Replace("'", "");
                        var sps = temp.Split(',');
                        if (sps.Length > 1)
                        {
                            dicMatch[sps[0]] = sps[1];
                        }
                    }

                    ms = Regex.Matches(result, "jh\\[\"R_\\d+\"\\]\\s+=[^;]+");

                    List<Models.Win007MatchModel> matchList = new List<Models.Win007MatchModel>();


                    foreach (Match m in ms)
                    {
                        var m4 = Regex.Match(m.Value, "jh\\[\"R_\\d+");
                        if (m4.Success)
                        {
                            HandleCaptureDataContent(Regex.Replace(m4.Value, "jh\\[\"R_", ""), m.Value, dicMatch, matchList);
                        }
                    }

                    _View.Log = $"解析完成.";
                    switch (_View.MatchSaveOption)
                    {
                        case Enums.Win007MatchSaveOptionEnum.NotSave:
                            {
                                if (isLoopMatch)
                                {
                                    _MatchList.AddRange(matchList);
                                    //matchList.ForEach(x => {
                                    //    if (_MatchList.Find(x2 => x2.Id == x.Id) == null)
                                    //    {
                                    //        _MatchList.Add(x);
                                    //    }
                                    //});
                                }
                                else
                                    _MatchList = matchList;
                            }
                            break;
                        case Enums.Win007MatchSaveOptionEnum.Save:
                            _MatchList.AddRange(matchList);
                            break;
                    }
                    //_View.AnalysisDataCaptureProgressMax = _MatchList.Count;
                    //if (_View.MatchSaveOption == Enums.Win007MatchSaveOptionEnum.NotSave && !isLoopMatch)
                    //{
                    //    var dt = _MatchList.ToDataTable();
                    //    foreach (DataRow row in dt.Rows)
                    //    {
                    //        var newrow = output.NewRow();
                    //        for (var i = 0; i < dt.Columns.Count; ++i)
                    //        {
                    //            newrow[i] = row[i];
                    //        }
                    //        output.Rows.Add(newrow);
                    //    }
                    //}
                } while (false);
            }

            _View.AnalysisDataCaptureProgressMax = _MatchList.Count;
            var dt = _MatchList.ToDataTable();
            foreach (DataRow row in dt.Rows)
            {
                var newrow = output.NewRow();
                for (var i = 0; i < dt.Columns.Count; ++i)
                {
                    newrow[i] = row[i];
                }
                output.Rows.Add(newrow);
            }
            return output;
        }

        public void InitDataCaptureWithAnalysis(bool saveLastData)
        {
            if (_MatchResultList == null)
                _MatchResultList = new List<Models.Win007MatchResultModel>();
            else
            {
                if (!saveLastData)
                    _MatchResultList = new List<Models.Win007MatchResultModel>();
            }
        }


        public DataTable GetAnalysisData(Models.GetAnalysisDataSearchOption option)
        {
            DataTable output = new DataTable();

            var columns = new Models.Win007MatchResultModel().GetDescriptions();
            foreach (var col in columns)
                output.Columns.Add(col, typeof(string));
            var dt = _MatchResultList.ToDataTable();

            Action<DataRow> funcSetRow = (row) =>
            {
                var newrow = output.NewRow();
                for (var i = 0; i < dt.Columns.Count; ++i)
                {
                    newrow[i] = row[i];
                }
                output.Rows.Add(newrow);
            };

            foreach (DataRow row in dt.Rows)
            {
                if (option.TypeList.Count > 0)
                {
                    if (option.TypeList.IndexOf(row["Type"].ToString()) != -1)
                    {
                        funcSetRow(row);
                    }
                }
                else
                {
                    funcSetRow(row);
                }
            }
            return output;
        }

        private List<Models.Win007MatchResultModel> AnalysisText(string html, string arrayName, Models.Win007MatchModel item)
        {
            List<Models.Win007MatchResultModel> matchResultList = new List<Models.Win007MatchResultModel>();

            do
            {

                var text = "";
                {
                    var m = Regex.Match(html, arrayName + "=\\[\\[[^;]+");
                    if (!m.Success)
                    {
                        _View.Log = "无法查找到赛事数据";
                        break;
                    }
                    text = m.Value.Substring((arrayName + "=[").Length);
                }

                {
                    var ms = Regex.Matches(text, "\\[[^\\]]+");
                    var index = 0;
                    foreach (Match m in ms)
                    {
                        var content = m.Value.TrimStart('[');
                        var sps = content.Split(',');
                        if (sps.Length > 12)
                        {
                            Func<string, string> funcGetValue = s =>
                            {
                                var r = Regex.Replace(s, "<[^>]+>", "");
                                r = Regex.Replace(r, "['0-9]+", "").Trim();
                                return r;
                            };
                            Func<string, string> funcGetText = s =>
                            {
                                return Regex.Replace(s, "['0-9]+", "").Trim();
                            };
                            ++index;
                            Models.Win007MatchResultModel model = new Models.Win007MatchResultModel()
                            {
                                MatchId = item.Id,
                                Type = funcGetText(sps[2]),
                                Date = sps[0].Replace("'", "").Trim(),
                                HomeTeam = funcGetValue(sps[5]),
                                VisitingTeam = funcGetValue(sps[7]),
                                Score = (sps[10]).Replace("'", "").Trim(),
                                Result = sps[12].Trim()
                            };
                            switch (model.Result)
                            {
                                case "0":
                                    model.Result = "平";
                                    break;
                                case "1":
                                    model.Result = "胜";
                                    break;
                                case "-1":
                                    model.Result = "负";
                                    break;
                                default:
                                    throw new Exception("不存在的值");
                            }

                            matchResultList.Add(model);

                            //if (matchResultList.Count == 10)
                            //    break;
                        }
                    }
                }

            } while (false);
            return matchResultList;
        }


        public Enums.CaptureStateEnum DataCaptureWithAnalysis(string matchId = "")
        {
            var output = Enums.CaptureStateEnum.NoMatch;
            try
            {
                do
                {
                    Models.Win007MatchModel item = null;

                    if (string.IsNullOrEmpty(matchId))
                        item = _MatchList.Find(s => s.State == 0);
                    else
                        item = _MatchList.Find(s => s.Id == matchId);

                    if (item == null)
                    {
                        output = Enums.CaptureStateEnum.Completed;
                        break;
                    }
                    //item = new Models.Win007MatchModel() { Id = "1247764", Time = "" };
                    var head = new HttpHead()
                    {
                        Url = $"http://zq.win007.com/analysis/{item.Id}.htm",
                        Method = "GET"
                    };
                    _View.Log = $"载入：{head.Url}({item.Time})";
                    var result = HttpHelper.SendHttpRequest(ref head);
                    if (result.Length == 0 || !head.Result_Success)
                    {
                        _View.Log = $"下载出错，状态码({head.Result_StatusCode})，出错信息：{head.Result_Exception}";
                        break;
                    }
                    _View.Log = "载入完成";

                    var hometeam = "";
                    var guestteam = "";
                    {
                        var ms = Regex.Matches(result, "hometeam=\\s*\"[^\"]+|guestteam=\\s*\"[^\"]+");
                        if (ms.Count != 2)
                        {
                            _View.Log = "无法获取主客队";
                            break;
                        }
                        hometeam = Regex.Replace(ms[0].Value, "hometeam=\\s*\"", "");
                        guestteam = Regex.Replace(ms[1].Value, "guestteam=\\s*\"", "");
                        item.AnalysisHomeTeam = hometeam;
                        item.AnalysisVisitingTeam = guestteam;
                    }

                    //var text = "";
                    //{
                    //    var m = Regex.Match(result, "v_data=\\[\\[[^;]+");
                    //    if (!m.Success)
                    //    {
                    //        _View.Log = "无法查找到赛事数据";
                    //        break;
                    //    }
                    //    text = m.Value.Substring("v_data=[".Length);
                    //}

                    //List<Models.Win007MatchResultModel> matchResultList = new List<Models.Win007MatchResultModel>();
                    //{
                    //    var ms = Regex.Matches(text, "\\[[^\\]]+");
                    //    var index = 0;
                    //    foreach (Match m in ms)
                    //    {
                    //        var content = m.Value.TrimStart('[');
                    //        var sps = content.Split(',');
                    //        if (sps.Length > 12)
                    //        {
                    //            Func<string, string> funcGetValue = s =>
                    //            {
                    //                var r = Regex.Replace(s, "<[^>]+>", "");
                    //                r = Regex.Replace(r, "['0-9]+", "");
                    //                return r;
                    //            };
                    //            Func<string, string> funcGetText = s => {
                    //                return Regex.Replace(s, "['0-9]+", "");
                    //            };
                    //            ++index;
                    //            Models.Win007MatchResultModel model = new Models.Win007MatchResultModel()
                    //            {
                    //                MatchId = item.Id,
                    //                Type = funcGetText(sps[2]),
                    //                Date = sps[0].Replace("'", "").Trim(),
                    //                HomeTeam = funcGetValue(sps[5]),
                    //                VisitingTeam = funcGetValue(sps[7]),
                    //                Score = (sps[10]).Replace("'", "").Trim(),
                    //                Result = sps[12]
                    //            };
                    //            switch (model.Result)
                    //            {
                    //                case "0":
                    //                    model.Result = "平";
                    //                    break;
                    //                case "1":
                    //                    model.Result = "胜";
                    //                    break;
                    //                case "-1":
                    //                    model.Result = "负";
                    //                    break;
                    //                default:
                    //                    throw new Exception("不存在的值");
                    //            }

                    //            matchResultList.Add(model);

                    //            //if (matchResultList.Count == 10)
                    //            //    break;
                    //        }
                    //    }
                    //}

                    List<Models.Win007MatchResultModel> home_matchResultList = null;
                    home_matchResultList = AnalysisText(result, "h2_data", item);
                    home_matchResultList.ForEach(s =>
                    {
                        s.IsHomeTeam = true;
                    });
                    if (_MatchResultList != null)
                        _MatchResultList.AddRange(home_matchResultList);

                    List<Models.Win007MatchResultModel> visiting_matchResultList = null;
                    visiting_matchResultList = AnalysisText(result, "a2_data", item);
                    visiting_matchResultList.ForEach(s =>
                    {
                        s.IsHomeTeam = false;
                    });
                    if (_MatchResultList != null)
                        _MatchResultList.AddRange(visiting_matchResultList);

                    output = Enums.CaptureStateEnum.Success;
                    item.State = 1;

                    var count = _MatchList.Count(s => s.State == 0);
                    _View.Log = $"剩余{count}条数据待采集...";
                    _View.AnalysisDataCaptureProgressValue = _MatchList.Count - count;
                } while (false);
            }
            catch (Exception ex)
            {
                output = Enums.CaptureStateEnum.Exception;
                _View.Log = "发生异常：" + ex.Message;
            }
            switch (output)
            {
                case Enums.CaptureStateEnum.NoMatch:
                case Enums.CaptureStateEnum.Exception:
                    {
                        _ErrorStartTime = DateTime.Now;
                    }
                    break;
            }
            return output;
        }

        public DataTable FilterCaptureMatch(string id)
        {
            DataTable output = new DataTable();

            var columns = new Models.Win007MatchResultModel().GetDescriptions();
            foreach (var col in columns)
                output.Columns.Add(col, typeof(string));
            do
            {
                var filterMatchList = _View.FilterMatch;
                var outputList = new List<Models.Win007MatchResultModel>();
                if (_MatchList == null || _MatchList.Count == 0)
                {
                    _View.Log = "没有数据可供筛选";
                    break;
                }
                if (_MatchResultList == null)
                {
                    _View.Log = "当前赛事分析数据为空，请先执行采集";
                }
                else
                {

                    var ps = _MatchResultList.FindAll(s => s.MatchId == id && filterMatchList.IndexOf(s.Type) != -1).OrderByDescending(s => s.Date);
                    var h_ps = ps.Where(s => s.IsHomeTeam);
                    var v_ps = ps.Where(s => !s.IsHomeTeam);

                    Func<IEnumerable<Models.Win007MatchResultModel>, List<Models.Win007MatchResultModel>> funcGetFilterList = (iter) =>
                    {
                        List<Models.Win007MatchResultModel> resultList = new List<Models.Win007MatchResultModel>();
                        foreach (var p in iter)
                        {
                            resultList.Add(p);
                            if (resultList.Count == 10)
                                break;
                        }
                        return resultList;
                    };
                    outputList.AddRange(funcGetFilterList(h_ps));
                    outputList.AddRange(funcGetFilterList(v_ps));
                }
                var dt = outputList.ToDataTable();
                foreach (DataRow row in dt.Rows)
                {
                    var newrow = output.NewRow();
                    for (var i = 0; i < dt.Columns.Count; ++i)
                    {
                        newrow[i] = row[i];
                    }
                    output.Rows.Add(newrow);
                }

            } while (false);
            return output;
        }


        public DataTable FilterCaptureMatch()
        {
            DataTable output = new DataTable();

            var columns = new Models.Win007MatchModel().GetDescriptions();
            foreach (var col in columns)
                output.Columns.Add(col, typeof(string));
            do
            {
                var filterMatchList = _View.FilterMatch;
                if (_MatchList == null || _MatchList.Count == 0)
                {
                    _View.Log = "没有数据可供筛选";
                    break;
                }
                if (_MatchResultList == null)
                {
                    _View.Log = "当前赛事分析数据为空，请先执行采集";
                }
                else
                {
                    _MatchList.ForEach(item =>
                    {
                        var ps = _MatchResultList.FindAll(s => s.MatchId == item.Id && filterMatchList.IndexOf(s.Type) != -1).OrderByDescending(s => s.Date);
                        if (item.Id == "1212559")
                        {
                            string err = "";
                        }
                        var h_ps = ps.Where(s => s.IsHomeTeam);
                        var v_ps = ps.Where(s => !s.IsHomeTeam);

                        Func<IEnumerable<Models.Win007MatchResultModel>, List<Models.Win007MatchResultModel>> funcGetFilterList = (iter) =>
                        {
                            List<Models.Win007MatchResultModel> resultList = new List<Models.Win007MatchResultModel>();
                            foreach (var iter_item in iter)
                            {
                                if (iter_item.MatchId == "1130193")
                                {
                                    string err = "";
                                }
                                var newItem = new Models.Win007MatchResultModel();
                                foreach (var np in newItem.GetType().GetProperties())
                                {
                                    np.SetValue(newItem, np.GetValue(iter_item, null), null);
                                }
                                var ms = Regex.Matches(newItem.HomeTeam, "[^\\s]+");
                                if (ms.Count > 0)
                                    newItem.HomeTeam = ms[0].Value;

                                ms = Regex.Matches(newItem.VisitingTeam, "[^\\s]+");
                                if (ms.Count > 0)
                                    newItem.VisitingTeam = ms[0].Value;

                                resultList.Add(newItem);
                                if (resultList.Count == 10)
                                    break;
                            }
                            return resultList;
                        };

                        item.HomeTeam10Win = funcGetFilterList(h_ps).Count(s => s.Result == "胜" && (s.HomeTeam == item.AnalysisHomeTeam || (s.HomeTeam.StartsWith(item.AnalysisHomeTeam) )));

                        item.VisitingTeam10Win = funcGetFilterList(v_ps).Count(s => s.Result == "胜" && (s.VisitingTeam == item.AnalysisVisitingTeam || (s.VisitingTeam.StartsWith(item.AnalysisVisitingTeam) )));
                    });
                }
                var dt = _MatchList.ToDataTable();
                foreach (DataRow row in dt.Rows)
                {
                    var newrow = output.NewRow();
                    for (var i = 0; i < dt.Columns.Count; ++i)
                    {
                        newrow[i] = row[i];
                    }
                    output.Rows.Add(newrow);
                }

            } while (false);
            return output;
        }

        public bool IsCanExecNextCapture()
        {
            var span = (DateTime.Now - _ErrorStartTime);
            var output = span.TotalMinutes > 2;
            _View.WaitTime = $"{span.Minutes}:{span.Seconds}";
            return output;
        }

        public void CaptureMulMatchUrl(string id)
        {
            if (_TreeNodeDataIndexList != null)
            {
                var node = _TreeNodeDataIndexList.Find(x => x.Id == id);
                if (node != null)
                {

                    do
                    {
                        if (node.Node.IsOnlyTitle)
                        {
                            _View.Log = "当前赛事不是具体赛事";
                            break;
                        }
                        var head = new HttpHead()
                        {
                            Url = node.Node.Url,
                            Method = "GET"
                        };
                        _View.Log = $"正在请求：{head.Url}...";
                        var result = HttpHelper.SendHttpRequest(ref head);
                        _View.Log = "请求返回.";
                        if (result.Length == 0)
                        {
                            _View.Log = "服务器返回为空";
                            break;
                        }
                        if (!head.Result_Success)
                        {
                            _View.Log = $"服务器返回出错：{head.Result_Exception}";
                            break;
                        }

                        var selectSeason = "";
                        {
                            var m = Regex.Match(result, "selectSeason[^;]+");
                            if (m.Success)
                            {
                                m = Regex.Match(m.Value, "\\d+");
                                if (m.Success)
                                    selectSeason = m.Value;
                            }
                        }

                        List<string> urlList = new List<string>();
                        var arrLeague = "";
                        var mScriptLink = Regex.Match(result, "src=\"/jsData/matchResult[^\"]+");
                        if (mScriptLink.Success)
                        {
                            var link = mScriptLink.Value.Replace("src=\"", "");
                            head.Url = new Uri(new Uri(head.Url), link).ToString();
                            _View.Log = $"正在请求：{head.Url}...";
                            var result2 = HttpHelper.SendHttpRequest(ref head);
                            _View.Log = "请求返回.";
                            if (result2.Length == 0)
                            {
                                _View.Log = "服务器返回为空";
                                break;
                            }
                            if (!head.Result_Success)
                            {
                                _View.Log = $"服务器返回出错：{head.Result_Exception}";
                                break;
                            }
                            {
                                var m = Regex.Match(result2, "arrLeague[^,]+");
                                if (m.Success)
                                {
                                    arrLeague = Regex.Replace(m.Value, @"[A-Za-z=\s\[]+", "");
                                }
                            }

                            {
                                var m = Regex.Match(result2, "arrSubLeague[^;]+");
                                if (m.Success)
                                {
                                    var ms = Regex.Matches(m.Value, @"\[\d+,");
                                    foreach (Match m_item in ms)
                                    {
                                        var subSclassID = Regex.Replace(m_item.Value, @"[^\d]+", "");
                                        var url = $"/cn/SubLeague/{selectSeason}/{arrLeague}_" + subSclassID + ".html";
                                        url = new Uri(new Uri(head.Url), url).ToString();
                                        urlList.Add(url);
                                    }
                                }
                            }
                            if (urlList.Count > 1)
                            {
                                node.Node.Url = string.Join("|", urlList.ToArray());
                                _View.Log = "已获取到多次循环赛事.";
                            }
                            else
                            {
                                _View.Log = "当前赛事不是多次循环赛事.";
                            }
                        }
                    } while (false);
                }
            }
        }
    }
}
